import React, { useState, useEffect } from 'react';
import { Button, Descriptions, Input, Radio, Space, Steps, Table } from 'antd';
import './index.css';
import {TYRE_SELECTION} from "../../uitl/constant-filename";

const inputParamsInit1 = {
  planeWeightMax: null, // 飞机的最大总重(kg)
  suggestColumnNum: null, // 推荐立柱数量
  suggestTyreNum: null, // 推荐轮胎数量
  mainLandingGearMaxShutdownLoad: null, // 主起落架最大停机载荷(kN)
  planeMaxGroundSpeed: null, // 飞机地面最大速度(km/h)
  noseGearMaxShutdownLoad: null, // 前起落架最大停机载荷(kN)
  noseGearMaxFrontWheelLoadOfBrake: null, // 前起落架最大刹车的前轮载荷(kN)
}
const inputParamsInit2 = {
  planeWeightMax: 20400, // 飞机的最大总重(kg)
  suggestColumnNum: '1或2个', // 推荐立柱数量
  suggestTyreNum: '1或2个', // 推荐轮胎数量
  mainLandingGearMaxShutdownLoad: 80.05, // 主起落架最大停机载荷(kN)
  planeMaxGroundSpeed: 300, // 飞机地面最大速度(km/h)
  noseGearMaxShutdownLoad: 60.037, // 前起落架最大停机载荷(kN)
  noseGearMaxFrontWheelLoadOfBrake: 91.207, // 前起落架最大刹车的前轮载荷(kN)
}

function Index({}) {
  const [current, setCurrent] = useState(0); // 当前步骤
  const [canNext, setCanNext] = useState(true);

  const [inputParams, setInputParams] = useState(inputParamsInit1); // 输入参数
  const [readOnly, setReadOnly] = useState(false);

  const [theClosest01, setTheClosest01] = useState(null); // 最接近的数，主起落架
  const [theClosest02, setTheClosest02] = useState(null); // 最接近的数，前起落架

  // 输入参数的描述项
  const descriptionItems = [
    {
      key: 1,
      label: '飞机最大总重(kg)',
      span: 2,
      children: <Input name={'planeWeightMax'} onChange={onInputParamsChange} placeholder={"请输入"}
                       value={inputParams.planeWeightMax} readOnly={readOnly} />,
    },
    {
      key: 2,
      label: '推荐立柱数量',
      span: 2,
      children: <Input name={'suggestColumnNum'} onChange={onInputParamsChange} placeholder={"请输入"}
                       value={columnNumRecommand(inputParams.planeWeightMax)} readOnly />,
    },
    {
      key: 3,
      label: '推荐轮胎数量',
      span: 2,
      children: <Input name={'suggestTyreNum'} onChange={onInputParamsChange} placeholder={"请输入"}
                       value={tyreNumRecommand(inputParams.planeWeightMax)} readOnly />,
    },
    {
      key: 4,
      label: '主起落架最大停机载荷(kN)',
      span: 2,
      children: <Input name={'mainLandingGearMaxShutdownLoad'} onChange={onInputParamsChange}
                       value={inputParams.mainLandingGearMaxShutdownLoad}
                       placeholder={"请输入"} readOnly={readOnly} />,
    },
    {
      key: 5,
      label: '飞机地面最大速度(km/h)',
      span: 2,
      children: <Input name={'planeMaxGroundSpeed'} onChange={onInputParamsChange} placeholder={"请输入"}
                       value={inputParams.planeMaxGroundSpeed} readOnly={readOnly} />,
    },
    {
      key: 6,
      label: '前起落架最大停机载荷(kN)',
      span: 2,
      children: <Input name={'noseGearMaxShutdownLoad'} onChange={onInputParamsChange} placeholder={"请输入"}
                       value={inputParams.noseGearMaxShutdownLoad} readOnly={readOnly} />,
    },
    {
      key: 7,
      label: '前起落架最大刹车的前轮载荷(kN)',
      span: 4,
      children: <Input name={'noseGearMaxFrontWheelLoadOfBrake'} onChange={onInputParamsChange}
                       value={inputParams.noseGearMaxFrontWheelLoadOfBrake}
                       placeholder={"请输入"} readOnly={readOnly} />,
    },
  ];

  useEffect(() => {
    /* command argv */
    window.electronAPI.commandArgv((_event, content) => {
      const objs = JSON.parse(content);
      if (objs.length > 0) {
        setReadOnly(true);
        objs.forEach(obj => {
          if (obj.code === 'QLJ_W') {
            // 设计最大着陆重量
            inputParams.planeWeightMax = obj.value;
          }
          else if (obj.code === 'ZZDZH') {
            // 主起落架最大停机载荷
            inputParams.mainLandingGearMaxShutdownLoad = obj.value;
          }
          else if (obj.code === 'QZDZH') {
            // 前起落架最大停机载荷
            inputParams.noseGearMaxShutdownLoad = obj.value;
          }
          else if (obj.code === 'QZXZH') {
            // 最大刹车的前轮载荷
            inputParams.noseGearMaxFrontWheelLoadOfBrake = obj.value;
          }
          else if (obj.code === 'ZLSD') {
            // 最大着陆速度
            inputParams.planeMaxGroundSpeed = obj.value;
          }
        });
        setInputParams({ ...inputParams });
      }
      else {
        setReadOnly(false);

        setInputParams({ ...inputParamsInit2 });
      }
    });
  }, []);

  function columnNumRecommand(W) {
    if (W > 27200 && W < 79500) {
      return 2
    } else if (W > 107000 && W < 186000) {
      return 2
    } else if (W < 27200) {
      return '1或2'
    } else if (W > 227000) {
      return 4
    } else return 2;
  }

  function tyreNumRecommand(W) {
    if (W > 27200 && W < 79500) {
      return 2
    } else if (W > 107000 && W < 186000) {
      return 4
    } else if (W < 27200) {
      return '1或2'
    } else if (W > 227000) {
      return '此时增加支柱的轮胎数不足以缓和道面承载加大引起的矛盾，建议增加支柱数目'
    } else return 2;
  }

  /**
   * 修改输入参数
   * @param e
   */
  function onInputParamsChange(e) {
    const target = e.target;
    inputParams[target.name] = target.value;

    setInputParams({ ...inputParams });
  }

  /**
   * 步骤控制
   * @param num
   */
  function control(num) {
    let temp = current + num;
    if (temp >= 0 && temp <= 3) {
      setCurrent(current + num);
    }

    if (num > 0) {
      setCanNext(true);
    }
  }

  /** 步骤 1 相关 */
  const [mainLandingGearColumnNum, setMainLandingGearColumnNum] = useState(); // 主起落架立柱
  const [frontLandingGearColumnNum, setFrontLandingGearColumnNum] = useState(); // 前起落架立柱
  /** 主起落架立柱数量选择 */
  function mainLandingGearColumnNumChange(e) {
    setMainLandingGearColumnNum(e.target.value);
  }
  /** 前起落架立柱数量选择 */
  function frontLandingGearColumnNumChange(e) {
    setFrontLandingGearColumnNum(e.target.value);
  }


  /** 步骤 2 相关 */
  // 主起落架单个立柱轮胎
  const [mainLandingGearSingleColumnTireNum, setMainLandingGearSingleColumnTireNum] = useState();
  // 前起落架单个立柱轮胎
  const [frontLandingGearSingleColumnTireNum, setFrontLandingGearSingleColumnTireNum] = useState();
  /** 主起落架单个立柱轮胎数量选择 */
  function mainLandingGearSingleColumnTireNumChange(e) {
    setMainLandingGearSingleColumnTireNum(e.target.value);
  }
  /** 前起落架单个立柱轮胎数量选择 */
  function frontLandingGearSingleColumnTireNumChange(e) {
    setFrontLandingGearSingleColumnTireNum(e.target.value);
  }

  /** 找出最接近的数 */
  function findClosestNumber(step, num) {
    let arr;
    if (step === 3) {
      arr = mainLandingData.map(m => m.ratedLoad);
    }
    else if (step === 4) {
      arr = previousLandingData.map(m => m.ratedLoad);
    }

    let closest = arr[0]; // 初始化为第一个元素
    let diff = Math.abs(num - closest); // 初始化差值为第一个元素与num的差的绝对值

    for (let i = 1; i < arr.length; i++) {
      let newDiff = Math.abs(num - arr[i]);
      if (newDiff < diff) {
        diff = newDiff;
        closest = arr[i];
      }
    }

    return closest;
  }

  /** 步骤 3 相关 */
  const [mainLandingGearTireLoad, setMainLandingGearTireLoad] = useState(null); // 主起落架轮胎载荷
  /** 计算 */
  function calculateMainLandingGearTireLoad(step) {
    /* 主起落架轮胎载荷 */
    if (step === 3) {
      const res = inputParams.mainLandingGearMaxShutdownLoad * 1.25 / mainLandingGearSingleColumnTireNum;
      setMainLandingGearTireLoad(res);

      setTheClosest01(findClosestNumber(3, res));
    }
    /* 前起落架轮胎载荷 */
    else if (step === 4) {
      const preMaxLoad = inputParams.noseGearMaxShutdownLoad * 1.25 / frontLandingGearSingleColumnTireNum;
      const preBrakeLoad = inputParams.noseGearMaxFrontWheelLoadOfBrake * 1.25 / frontLandingGearSingleColumnTireNum;

      setNoseLandingGearTireShutdownLoad(preMaxLoad);
      setNoseLandingGearBrakeLoad(preBrakeLoad);
      setOverlappingValueOfParkingAndBrakingLoad(preMaxLoad + preBrakeLoad);

      setTheClosest02(findClosestNumber(4, preMaxLoad + preBrakeLoad));
    }
  }
  // 输入参数的描述项
  const mainLandingGearTireLoadDescriptions = [
    {
      key: 1,
      label: '主起落架轮胎载荷(kN)',
      span:2,
      children: <div>{mainLandingGearTireLoad}</div>,
    }
  ];

  const [mainWheelsSelect, setMainWheelsSelect] = useState(null);
  const rowSelection01 = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      console.log('set Main Wheels Select:', selectedRows);
      setMainWheelsSelect(selectedRows);
    },
  }

  const rowClassName = (record, index) => {
    if (index % 2 === 1) {
      return 'highlight-row'; // 当条件满足时，返回高亮类的类名
    }
    return '';
  };

  const onRow01 = (record, rowIndex) => {
    return {
      style: { backgroundColor: record.ratedLoad === theClosest01 ? '#bae7ff' : '' }, // 高亮颜色
    };
  };

  const [filters, setFilters] = useState([]);
  const columns = [
    {
      title: '序号', dataIndex: 'listNumber', key: 'listNumber',
      render: (val, record, index) => index+1,width: "5%", align: "center",
    },
    {
      title: '类型',
      dataIndex: 'type',
      key: 'type',
      showSorterTooltip: {
        target: 'full-header',
      },
      align: "center",
      filters: filters,
      onFilter: (value, record) => record.type.indexOf(value) === 0,
    },
    {
      title: '尺寸(×25.4)(mm×mm)',
      dataIndex: 'size',
      key: 'size',
      align: "center",
    },
    {
      title: '额定层数',
      dataIndex: 'ratedLayers',
      key: 'ratedLayers',
      align: "center",
    },
    {
      title: '额定载荷(kN)',
      dataIndex: 'ratedLoad',
      key: 'ratedLoad',
      align: "center",
      sorter: (a, b) => a.ratedLoad- b.ratedLoad,
    },
    {
      title: '充气压力(×6895)(Pa)',
      dataIndex: 'inflationPressure',
      key: 'inflationPressure',
      align: "center",
      sorter: (a, b) => a.InflationPressure- b.InflationPressure,
    },
    {
      title: '额定速度(×0.447)(m/s)',
      dataIndex: 'ratedVelocity',
      key: 'ratedVelocity',
      align: "center",
      sorter: (a, b) => a.ratedVelocity- b.ratedVelocity,
    },
    {
      title: '最大直径(×25.4)(mm)',
      dataIndex: 'maxDiameter',
      key: 'maxDiameter',
      align: "center",
      sorter: (a, b) => a.maxDiameter- b.maxDiameter,
    },
    {
      title: '最大宽度(×25.4)(mm)',
      dataIndex: 'maxWidth',
      key: 'maxWidth',
      align: "center",
      sorter: (a, b) => a.maxWidth- b.maxWidth,
    },
    {
      title: '重量(×0.454)(kg)',
      dataIndex: 'weight',
      key: 'weight',
      align: "center",
      sorter: (a, b) => a.weight- b.weight,
    },
  ];
  const [mainLandingData, setMainLandingData] = useState([]);
  const [previousLandingData, setPreviousLandingData] = useState([]);

  /** 步骤 4 相关 */
  const onRow02 = (record, rowIndex) => {
    return {
      style: { backgroundColor: record.ratedLoad === theClosest02 ? '#bae7ff' : '' }, // 高亮颜色
    };
  };
  // 前起落架轮胎停机载荷(kN)
  const [noseLandingGearTireShutdownLoad, setNoseLandingGearTireShutdownLoad] = useState(null);
  // 前起落架刹车载荷(kN)
  const [noseLandingGearBrakeLoad, setNoseLandingGearBrakeLoad] = useState(null);
  // 停机与刹车载荷叠加值(kN)
  const [overlappingValueOfParkingAndBrakingLoad,
    setOverlappingValueOfParkingAndBrakingLoad] = useState(null);

  const noseLandingGearTireChoiceDescriptions = [
    {
      key: 1,
      span: 4,
      label: '前起落架轮胎停机载荷(kN)',
      children: <div>{noseLandingGearTireShutdownLoad}</div>
    },
    {
      key: 1,
      span: 4,
      label: '前起落架刹车载荷(kN)',
      children: <div>{noseLandingGearBrakeLoad}</div>
    },
    {
      key: 1,
      span: 4,
      label: '停机与刹车载荷叠加值(kN)',
      children: <div>{overlappingValueOfParkingAndBrakingLoad}</div>
    }
  ];

  const [previousWheelsSelect, setPreviousWheelsSelect] = React.useState(null)
  const rowSelection02 = {
    type: 'radio',
    onChange: (selectedRowKeys, selectedRows) => {
      setPreviousWheelsSelect(selectedRows);
    },
  }

  // 步骤标题及内容
  const steps = [
    {
      title: '单个起落架支柱数选择',
      content: <div>
        <div className={"sub-title"}>主起落架立柱数量选择</div>
        <Radio.Group onChange={mainLandingGearColumnNumChange} value={mainLandingGearColumnNum}>
          <Space direction="vertical">
            <Radio value={1}>1个立柱</Radio>
            <Radio value={2}>2个立柱</Radio>
            <Radio value={4}>4个立柱</Radio>
          </Space>
        </Radio.Group>

        <div className={"sub-title"}>前起落架立柱数量选择</div>
        <Radio.Group onChange={frontLandingGearColumnNumChange} value={frontLandingGearColumnNum}>
          <Space direction="vertical">
            <Radio value={1}>1个立柱</Radio>
            <Radio value={2}>2个立柱</Radio>
            <Radio value={4}>4个立柱</Radio>
          </Space>
        </Radio.Group>
      </div>,
    },
    {
      title: '单个支柱轮胎数选择',
      content: <div>
        <div className={"sub-title"}>主起落架单个立柱轮胎数量选择</div>
        <Radio.Group
          onChange={mainLandingGearSingleColumnTireNumChange}
          value={mainLandingGearSingleColumnTireNum}
        >
          <Space direction="vertical">
            <Radio value={1}>1个轮胎</Radio>
            <Radio value={2}>2个轮胎</Radio>
            <Radio value={4}>4个轮胎</Radio>
          </Space>
        </Radio.Group>

        <div className={"sub-title"}>前起落架单个立柱轮胎数量选择</div>
        <Radio.Group
          onChange={frontLandingGearSingleColumnTireNumChange}
          value={frontLandingGearSingleColumnTireNum}
        >
          <Space direction="vertical">
            <Radio value={1}>1个轮胎</Radio>
            <Radio value={2}>2个轮胎</Radio>
            <Radio value={4}>4个轮胎</Radio>
          </Space>
        </Radio.Group>
      </div>,
    },
    {
      title: '主起落架轮胎选择',
      content: <div>
        <div>
          <span className={"sub-title"}>计算结果</span>
          <Button
            type={"text"}
            onClick={calculateMainLandingGearTireLoad.bind(this, 3)}
            style={{color: "#1677FF"}}>
            计算
          </Button>
        </div>
        <Descriptions bordered={true} items={mainLandingGearTireLoadDescriptions} column={4} />

        <div className={"sub-title"}>前起落架轮胎选型（参考计算结果）</div>
        <Table
          rowKey={"id"}
          rowSelection={rowSelection01}
          columns={columns}
          dataSource={mainLandingData}
          onRow={onRow01}
          rowClassName={rowClassName}
          stripe
        />
      </div>,
    },
    {
      title: '前起落架轮胎选择',
      content: <div>
        <div>
          <span className={"sub-title"}>计算结果</span>
          <Button
            type={"text"}
            onClick={calculateMainLandingGearTireLoad.bind(this, 4)}
            style={{color: "#1677FF"}}>
            计算
          </Button>
        </div>
        <Descriptions bordered={true} items={noseLandingGearTireChoiceDescriptions} column={4} />

        <div className={"sub-title"}>前起落架轮胎选型（参考计算结果）</div>
        <Table
          rowKey={"id"}
          rowSelection={rowSelection02}
          columns={columns}
          onRow={onRow02}
          rowClassName={rowClassName}
          dataSource={previousLandingData}
        />
      </div>,
    },
  ];

  // 步骤标题
  const stepTitles = steps.map((item) => ({
    key: item.title,
    title: item.title,
  }));

  function categorizeItems(items) {
    const categorized = items.reduce((acc, item) => {
      if (!acc[item.category]) {
        acc[item.category] = [];
      }
      acc[item.category].push(item);
      return acc;
    }, {});

    return {
      mainLanding: categorized.mainLanding || [],
      previousLanding: categorized.previousLanding || [],
    };
  }

  useEffect(() => {
    window.electronAPI.reqAllTyre();
    window.electronAPI.resAllTyre((event, res) => {
      const categorizedResult = categorizeItems(res);
      setMainLandingData(categorizedResult.mainLanding);
      setPreviousLandingData(categorizedResult.previousLanding);

      setTimeout(() => {

      }, 1000);

      const originalArray = res.map(item => item.type);
      // 使用Set去重
      const uniqueSet = new Set(originalArray);
      // 将Set转换回数组，并映射到对象数组，其中每个对象都有一个value属性
      const uniqueArrayObjects = Array.from(uniqueSet).map(value => ({ value, text:value }));
      setFilters(uniqueArrayObjects);
    });
  }, []);

  // 0
  useEffect(() => {
    if (current === 0 && mainLandingGearColumnNum && frontLandingGearColumnNum) {
      setCanNext(false);
    }
  }, [mainLandingGearColumnNum, frontLandingGearColumnNum, current]);

  // 1
  useEffect(() => {
    if (current === 1 && mainLandingGearSingleColumnTireNum && frontLandingGearSingleColumnTireNum) {
      setCanNext(false);
    }
  }, [mainLandingGearSingleColumnTireNum, frontLandingGearSingleColumnTireNum, current]);

  // 2
  useEffect(() => {
    if (current === 2 && mainWheelsSelect) {
      setCanNext(false);
    }
  }, [mainWheelsSelect, current]);

  function finish() {
    const obj = [
      {
        id: '标识',
        name: '名称',
        code: '代号',
        value: '值'
      },
      {
        id: "193",
        name: '主轮胎类型',
        code: 'ZLTLX',
        value: mainWheelsSelect[0].type
      },
      {
        id: "194",
        name: '主轮胎尺寸',
        code: 'ZCC',
        value: mainWheelsSelect[0].size
      },
      {
        id: "195",
        name: '主轮胎额定层数',
        code: 'ZEDCS',
        value: mainWheelsSelect[0].ratedLayers
      },
      {
        id: "196",
        name: '主轮胎额定载荷',
        code: 'ZEDZH',
        value: mainWheelsSelect[0].ratedLoad
      },
      {
        id: "197",
        name: '主轮胎充气压力',
        code: 'ZCQYL',
        value: mainWheelsSelect[0].inflationPressure
      },
      {
        id: "198",
        name: '主轮胎额定速度',
        code: 'ZEDSD',
        value: mainWheelsSelect[0].ratedVelocity
      },
      {
        id: "199",
        name: '主轮胎最大直径',
        code: 'ZZDZJ',
        value: mainWheelsSelect[0].maxDiameter
      },
      {
        id: "200",
        name: '主轮胎最大宽度',
        code: 'ZZDKD',
        value: mainWheelsSelect[0].maxWidth
      },
      {
        id: "201",
        name: '主轮胎重量',
        code: 'ZZL',
        value: mainWheelsSelect[0].weight
      },
      {
        id: "271",
        name: '前轮胎类型',
        code: 'PLTLX',
        value: previousWheelsSelect[0].type
      },
      {
        id: "270",
        name: '前轮胎尺寸',
        code: 'PCC',
        value: previousWheelsSelect[0].size
      },
      {
        id: "268",
        name: '前轮胎额定层数',
        code: 'PEDCS',
        value: previousWheelsSelect[0].ratedLayers
      },
      {
        id: "267",
        name: '前轮胎额定载荷',
        code: 'PEDZH',
        value: previousWheelsSelect[0].ratedLoad
      },
      {
        id: "269",
        name: '前轮胎充气压力',
        code: 'PCQYL',
        value: previousWheelsSelect[0].inflationPressure
      },
      {
        id: "266",
        name: '前轮胎额定速度',
        code: 'PEDSD',
        value: previousWheelsSelect[0].ratedVelocity
      },
      {
        id: "264",
        name: '前轮胎最大直径',
        code: 'PZDZJ',
        value: previousWheelsSelect[0].maxDiameter
      },
      {
        id: "265",
        name: '前轮胎最大宽度',
        code: 'PZDKD',
        value: previousWheelsSelect[0].maxWidth
      },
      {
        id: "263",
        name: '前轮胎质量',
        code: 'PZL',
        value: previousWheelsSelect[0].weight
      },
      {
        id: "202",
        name: '主起落架N倍停机载荷下轮胎变形',
        code: 'LT_St',
        value: 0.12
      }, {
        id: "279",
        name: '前起落架N倍停机载荷下轮胎变形',
        code: 'QLT_St',
        value: 0.055
      },
      {
        id: "203",
        name: '轮胎效率',
        code: 'HCQ_nt',
        value: 0.47
      },
      {
        id: "204",
        name: '缓冲器效率',
        code: 'HCQ_ns',
        value: 0.7
      },
      {
        id: "254",
        name: '机身过载',
        code: 'overload',
        value: 3
      },
      {
        id: "257",
        name: '飞行器重力',
        code: 'QLJ_G',
        value: 3.05
      }
    ];

    window.electronAPI.createOutputFile(obj, TYRE_SELECTION);
  }

  return <div className={"tyre-selection"}>
    <Steps current={current} items={stepTitles} />

    <div className={"sub-title"}>输入参数</div>
    <Descriptions bordered items={descriptionItems} column={4} />

    <div>{steps[current].content}</div>

    <div className={"control"}>
      {
        current > 0 &&
        <Button type={"dashed"} className={"control-btn"} onClick={control.bind(this, -1)}>
          上一步
        </Button>
      }
      {
        current < 3 &&
        <Button type={"primary"} className={"control-btn"} disabled={canNext} onClick={control.bind(this, 1)}>
          下一步
        </Button>
      }
      {
        current >= 3 &&
        <Button type={"primary"} className={"control-btn"} onClick={finish}>
          完成
        </Button>
      }
    </div>
  </div>
}

export default Index;
